var express = require('express');
var router = express.Router();
var passport = require('passport');
var fs = require('fs');

var icon = fs.readFileSync('public/img/sun.ico');
var util = require('./util.js');

var background = [];
/* GET home page. */
router.get('/', function(req, res, next) {
	res.render("index", {
		sub_title: "Index"
	});
});

router.get('/favicon.ico', function(req, res, next) {
	res.send(icon);
});

router.route('/login')
	.get(function(req, res) {
		var bg = randomBG();
		res.render("login", {
			error: req.flash("error"),
			bg: bg,
			sub_title: "Login"
		});
	})

	.post(passport.authenticate('local', {
		failureRedirect: '/login',
		failureFlash: true
	}), function(req, res) {
		res.redirect('/');
	});

router.get('/profile', function(req, res) {
	res.render('user/profile', {
		user: req.user
	});
});

router.get('/logout', function(req, res) {
	req.logout();
	res.redirect("/login");
});

var randomBG = function() {
	if(background == undefined || background.length == 0) {
		background = util.initImgArray('/public/img/bg/');
	}
	return background[parseInt(Math.random() * background.length)];
}

module.exports = router;